package com.jgads.ad.sdk.mediation.adapter;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.interstitial.MediationCustomInterstitialLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.jgads.ad.sdk.mediation.utils.ThreadUtils;
import com.junion.ad.BidLossNotice;
import com.junion.ad.InterstitialAd;
import com.junion.ad.bean.InterstitialAdInfo;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.InterstitialAdListener;

import java.util.Map;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 12/23/21 6:07 PM
 */
public class CustomerInterstitialAdapter extends MediationCustomInterstitialLoader {

    private InterstitialAd interstitialAd;
    private InterstitialAdInfo interstitialAdInfo;

    @Override
    public void load(final Context context, AdSlot gmAdSlotInterstitial, final MediationCustomServiceConfig gmCustomServiceConfig) {
        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                interstitialAd = new InterstitialAd(context);
                interstitialAd.setListener(new InterstitialAdListener() {
                    @Override
                    public void onAdReceive(InterstitialAdInfo adInfo) {
                        interstitialAdInfo = adInfo;
                        if (isClientBidding() && adInfo != null) {//bidding广告类型
                            //bidding广告成功回调，回传竞价广告价格 单位：分
                            callLoadSuccess(adInfo.getBidPrice());
                        } else {
                            //普通广告成功回调
                            callLoadSuccess();
                        }
                    }

                    @Override
                    public void onAdExpose(InterstitialAdInfo adInfo) {
                        callInterstitialShow();
                    }

                    @Override
                    public void onAdClick(InterstitialAdInfo adInfo) {
                        callInterstitialAdClick();
                    }

                    @Override
                    public void onAdClose(InterstitialAdInfo adInfo) {
                        callInterstitialClosed();
                    }

                    @Override
                    public void onAdFailed(JUnionError error) {
                        callLoadFail(error.getCode(), error.getError());
                    }

                    @Override
                    public void onVideoStart(InterstitialAdInfo interstitialAdInfo) {
                    }

                    @Override
                    public void onVideoFinish(InterstitialAdInfo interstitialAdInfo) {
                    }

                    @Override
                    public void onVideoPause(InterstitialAdInfo interstitialAdInfo) {
                    }

                    @Override
                    public void onVideoError(InterstitialAdInfo interstitialAdInfo) {
                    }
                });
                if (gmCustomServiceConfig != null) {
                    interstitialAd.loadAd(gmCustomServiceConfig.getADNNetworkSlotId());
                }
            }
        });

    }

    /**
     * show在主线程中回调
     */
    @Override
    public void showAd(final Activity activity) {
        Log.i(Const.TAG, "showAd "+ Thread.currentThread().toString());
        if (interstitialAdInfo != null && activity != null && !activity.isFinishing()) {
            if (isClientBidding() && !interstitialAdInfo.isReportBidWin()) {
                interstitialAdInfo.sendWinNotice(interstitialAdInfo.getBidPrice());
            }
            interstitialAdInfo.showInterstitial(activity);
        }
    }

    @Override
    public MediationConstant.AdIsReadyStatus isReadyCondition() {
        if (interstitialAdInfo != null && !interstitialAdInfo.isOvertime()) {
            return MediationConstant.AdIsReadyStatus.AD_IS_READY;
        } else {
            if (interstitialAdInfo != null && interstitialAdInfo.isOvertime()) {
                return MediationConstant.AdIsReadyStatus.AD_IS_EXPIRED; // 注意这里是AD_IS_EXPIRED
            }
            return MediationConstant.AdIsReadyStatus.AD_IS_NOT_READY;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (interstitialAd != null) {
            interstitialAd.release();
            interstitialAd = null;
        }
        if (interstitialAdInfo != null) {
            interstitialAdInfo.release();
            interstitialAdInfo = null;
        }
    }

    /**
     * @param win         是否在本次竞价中获胜
     * @param winnerPrice 获胜者价格，可能为0 ,如果没有胜出则该值是-1
     * @param loseReason  竞价失败原因 1:价格较低 2：广告返回超时 10001：其他；如果胜出则该值是-1
     * @param extra       扩展参数
     */
    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        Log.i(Const.TAG,
                "receiveBidResult   win = "+ win+"  "+
                        "winnerPrice = "+winnerPrice +"  "+
                        "loseReason = " +loseReason  +"  "+
                        Thread.currentThread().toString());
        if (win) {
            //竞价成功
            if (interstitialAdInfo != null && !interstitialAdInfo.isReportBidWin()) {
                interstitialAdInfo.sendWinNotice((int) winnerPrice);
            }
        } else {
            //竞价失败
            if (interstitialAdInfo != null) {
                if (loseReason == 1) {
                    interstitialAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.LOW_PRICE);
                } else {
                    interstitialAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.OTHER);
                }
            }
        }
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

}
